/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦，本文采用木兰宽松许可证第2版]
 * 
 * https://zhiqim.org/project/zhiqim_products/gitsolo.htm
 *
 * gitsolo is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.zhiqim.gitsolo.action;

import java.sql.Timestamp;
import java.util.List;

import org.zhiqim.git.Git;
import org.zhiqim.git.util.Gits;
import org.zhiqim.gitsolo.Gitsolo;
import org.zhiqim.gitsolo.GitsoloConstants;
import org.zhiqim.gitsolo.dao.GitMemberDao;
import org.zhiqim.gitsolo.dao.GitProjectDao;
import org.zhiqim.gitsolo.dbo.GitRepository;
import org.zhiqim.gitsolo.dbo.GitRepositoryEx;
import org.zhiqim.httpd.HttpRequest;
import org.zhiqim.httpd.context.extend.StdSwitchAction;
import org.zhiqim.httpd.validate.ones.IsAlphaNumericUrlLen;
import org.zhiqim.httpd.validate.ones.IsIntegerValue;
import org.zhiqim.httpd.validate.ones.IsLen;
import org.zhiqim.httpd.validate.ones.IsNotEmpty;
import org.zhiqim.kernel.util.Ids;
import org.zhiqim.kernel.util.Sqls;
import org.zhiqim.kernel.util.Strings;
import org.zhiqim.kernel.util.Validates;
import org.zhiqim.orm.ORM;
import org.zhiqim.orm.dbo.Selector;

/**
 * 仓库管理，支持仓库的创建、删除和修改权限
 *
 * @version v1.0.0 @author zhichenggang 2014-3-21 新建与整理
 */
public class RepositoryAction extends StdSwitchAction implements GitsoloConstants
{
    @Override
    protected void validateId(HttpRequest request)
    {
        request.addValidate(new IsNotEmpty("repositoryId", "请选择一个选项"));
    }

    @Override
    protected void validateForm(HttpRequest request)
    {
        request.addValidate(new IsAlphaNumericUrlLen("repositoryCode", "仓库编码必须为字母,数字或(.-_~)组合，[1, 32]范围", 1, 32));
        request.addValidate(new IsLen("repositoryName", "仓库名称不能为空，[1, 32]范围", 1, 32));
        request.addValidate(new IsIntegerValue("repositorySeq", "仓库排序必须是[0, 999999]范围的非负整数", 0, 999999));
        request.addValidate(new IsNotEmpty("repositoryUpdateRole", "请选择仓库提交角色"));
        request.addValidate(new IsNotEmpty("repositoryCommitRole", "请选择仓库提交角色"));
    }

    @Override
    protected void list(HttpRequest request) throws Exception
    {
        Selector selector = new Selector();
        selector.addMust("projectId", GitProjectDao.getProjectId(request));
        selector.addOrderbyAsc("repositorySeq");
        List<GitRepositoryEx> list = ORM.view().list(GitRepositoryEx.class, selector);

        request.setAttribute("list", list);
        request.setAttribute("gitPreUrl", Strings.trimRight(request.getRequestURL(), request.getPathInContext()));
    }
    
    @Override
    protected void add(HttpRequest request) throws Exception
    {
    }

    @Override
    protected void modify(HttpRequest request) throws Exception
    {
        long repositoryId = request.getParameterLong("repositoryId");
        GitRepository item = ORM.table().item(GitRepository.class, repositoryId);
        if(item == null)
        {
            request.returnHistory("仓库不存在，请重新选择");
            return;
        }
        
        if (!GitProjectDao.chkProjectId(request, item.getProjectId()))
        {//判断是否切换了默认项目
            return;
        }
        
        request.setAttribute("item", item);
    }

    @Override
    protected void insert(HttpRequest request) throws Exception
    {
        long projectId = GitProjectDao.getProjectId(request);
        String operatorCode = request.getSessionName();
        
        String repositoryCode = request.getParameter("repositoryCode");
        String repositoryName = request.getParameter("repositoryName");
        int repositorySeq = request.getParameterInt("repositorySeq");
        String repositoryUpdateRole = request.getParameter("repositoryUpdateRole");
        String repositoryCommitRole = request.getParameter("repositoryCommitRole");
        
        if (!Validates.isFileName(repositoryCode))
        {
            request.returnHistory("仓库编码不合法，请重选一个编码");
            return;
        }
        
        Selector selector = new Selector();
        selector.addMust("projectId", projectId);
        selector.addMust("repositoryCode", repositoryCode);
        if(ORM.table().count(GitRepository.class, selector) > 0)
        {
            request.returnHistory("仓库编码["+repositoryCode+"]已存在，请重选一个编码");
            return;
        }
        
        String repositoryPath = Gitsolo.getRepositoryPath(projectId, repositoryCode);
        Git git = Gits.create(repositoryPath, operatorCode, operatorCode+"@gitsolo.com");
        if(git == null)
        {
            request.returnHistory("仓库创建文件存储["+repositoryPath+"]时失败，请联系管理检查");
            return;
        }
        
        Timestamp time = Sqls.nowTimestamp();
        GitRepository repo = new GitRepository();
        repo.setRepositoryId(Ids.longId());
        repo.setProjectId(projectId);
        repo.setRepositoryCode(repositoryCode);
        repo.setRepositoryName(repositoryName);
        repo.setRepositorySeq(repositorySeq);
        repo.setRepositoryUpdateRole(repositoryUpdateRole);
        repo.setRepositoryCommitRole(repositoryCommitRole);
        repo.setRepositoryCreator(operatorCode);
        repo.setRepositoryCreated(time);
        repo.setRepositoryModified(time);
        
        ORM.table().insert(repo);
        
        GitMemberDao.report(request, projectId, operatorCode, "创建了仓库", repositoryName);        
    }

    @Override
    protected void update(HttpRequest request) throws Exception
    {
        long repositoryId = request.getParameterLong("repositoryId");
        GitRepository item = ORM.table().item(GitRepository.class, repositoryId);
        if(item == null)
        {
            request.returnHistory("仓库不存在，请重新选择");
            return;
        }
        
        if (!GitProjectDao.chkProjectId(request, item.getProjectId()))
        {//判断是否切换了默认项目
            return;
        }
        
        String repositoryName = request.getParameter("repositoryName");
        String repositoryUpdateRole = request.getParameter("repositoryUpdateRole");
        String repositoryCommitRole = request.getParameter("repositoryCommitRole");
        int repositorySeq = request.getParameterInt("repositorySeq");
        
        item.setRepositoryName(repositoryName);
        item.setRepositoryUpdateRole(repositoryUpdateRole);
        item.setRepositoryCommitRole(repositoryCommitRole);
        item.setRepositorySeq(repositorySeq);
        item.setRepositoryModified(Sqls.nowTimestamp());
        ORM.table().update(item);
        
        GitMemberDao.report(request, GitProjectDao.getProjectId(request), request.getSessionName(), "修改了仓库", repositoryName);
    }

    @Override
    protected void delete(HttpRequest request) throws Exception
    {
        long repositoryId = request.getParameterLong("repositoryId");
        GitRepository item = ORM.table().item(GitRepository.class, repositoryId);
        if(item == null)
        {
            request.returnHistory("仓库不存在，请重新选择");
            return;
        }
        
        if (!GitProjectDao.chkProjectId(request, item.getProjectId()))
        {//判断是否切换了默认项目
            return;
        }
        
        Gits.delete(Gitsolo.getRepositoryPath(item.getProjectId(), item.getRepositoryCode()));
        ORM.table().delete(GitRepository.class, repositoryId);
        
        GitMemberDao.report(request, GitProjectDao.getProjectId(request), request.getSessionName(), "删除了仓库", item.getRepositoryName());
    }
}
